//
//  Created by wdj on 17/9/18.
//

#import "PGTabBarController.h"
#import "PGNavigationController.h"

#import "HotArticleVC.h"
#import "MineVC.h"
#import "RewardHallVC.h"
#import "APPCenterVC.h"
//#import "SecondVC.h"
//#import "ReceiveFastOrderVC.h"

@interface PGTabBarController ()<UITabBarControllerDelegate>

@property (nonatomic, strong) NSMutableArray *items;

@end

@implementation PGTabBarController

//懒加载items；
- (NSMutableArray *)items
{
    if (!_items) {
        _items = [NSMutableArray array];
    }
    return _items;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置item文字属性
    [self setUpItemAttrs];
    
    //初始化所有的子控制器
    [self setUpAllChildVces];
    
    self.delegate = self;
//    [self checkVersion];   //检测升级
    
}

-(void)checkVersion
{
    
    dispatch_queue_t queue =  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        
        NSURL *url = nil;
        //这个URL地址是该app在iTunes connect里面的相关配置信息。其中id是该app在app store唯一的ID编号。
        url = [NSURL URLWithString:@"http://itunes.apple.com/cn/lookup?id=1154370259"];
        NSString *jsonResponseString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新
            NSString *newVersion;
//            LoLog(@"通过appStore获取的数据信息：%@",jsonResponseString);
            
            NSData *data = [jsonResponseString dataUsingEncoding:NSUTF8StringEncoding];
            
            //    解析json数据
            id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSArray *array = json[@"results"];
            
            for (NSDictionary *dic in array) {
                
                newVersion = [dic valueForKey:@"version"];
                
            }
            
            NSLog(@"通过appStore获取的版本号是：%@",newVersion);
            
            //获取本地软件的版本号
            NSString *localVersion = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
            
            NSString *msg = [NSString stringWithFormat:@"你当前的版本是V%@，发现新版本V%@，是否下载新版本？",localVersion,newVersion];
            
            //对比发现的新版本和本地的版本
            if ([newVersion floatValue] > [localVersion floatValue])
            {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"升级提示"message:msg preferredStyle:UIAlertControllerStyleAlert];
                
                [self presentViewController:alert animated:YES completion:nil];
                
                [alert addAction:[UIAlertAction actionWithTitle:@"现在升级" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/quan-min-cheng-che-si-ji-duan/id1154370259?mt=8"]];
//                    LoLog(@"点击现在升级按钮");
                }]];
                
                [alert addAction:[UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                    LoLog(@"点击下次再说按钮");
                }]];
                
                
            }
            
        });
    });
    
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refresh" object:nil userInfo:nil];
}

- (void)setUpItemAttrs
{
    UITabBarItem *item = [UITabBarItem appearance];
    
    //正常时文字属性
    NSMutableDictionary *normalAtr = [NSMutableDictionary dictionary];
    normalAtr[NSFontAttributeName] = [UIFont systemFontOfSize:12];
    normalAtr[NSForegroundColorAttributeName] = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [item setTitleTextAttributes:normalAtr forState:UIControlStateNormal];
    
    //选中时文字属性
    NSMutableDictionary *selAtr = [NSMutableDictionary dictionary];
    selAtr[NSForegroundColorAttributeName] = [UIColor colorWithRed:235/255.0 green:107/255.0 blue:68/255.0 alpha:1.0];
    [item setTitleTextAttributes:selAtr forState:UIControlStateSelected];
    
}

- (void)setUpAllChildVces
{
    //悬赏大厅
//    UIStoryboard *RewardHallSB = [UIStoryboard storyboardWithName:@"HotArticle" bundle:nil];
    RewardHallVC *rewardHallVC = [[RewardHallVC alloc] init];
    
    //热推文章
    UIStoryboard *hotArticleSB = [UIStoryboard storyboardWithName:@"HotArticle" bundle:nil];
    HotArticleVC *hotArticleVC = [hotArticleSB instantiateViewControllerWithIdentifier:@"HotArticleVC"];

    //应用中心
//    UIStoryboard *appCenerSB = [UIStoryboard storyboardWithName:@"HotArticle" bundle:nil];
//    HotArticleVC *appCenerVC = [appCenerSB instantiateViewControllerWithIdentifier:@"HotArticleVC"];
    APPCenterVC *appCenerVC = [[APPCenterVC alloc] init];
    
    //我的
    UIStoryboard *mineSB = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
    MineVC *mineVC = [mineSB instantiateViewControllerWithIdentifier:@"MineVC"];
    
    [self setUpChildVc:rewardHallVC title:@"悬赏大厅" image:@"tabBar_wode" selImage:@"tabBar_wode_lighted"];
    [self setUpChildVc:hotArticleVC title:@"热推文章" image:@"tabBar_wode" selImage:@"tabBar_wode_lighted"];
    [self setUpChildVc:appCenerVC title:@"应用中心" image:@"tabBar_wode" selImage:@"tabBar_wode_lighted"];
    [self setUpChildVc:mineVC title:@"我的" image:@"tabBar_wode" selImage:@"tabBar_wode_lighted"];
    
    
    
}

- (void)setUpChildVc:(UIViewController *)vc title:(NSString *)title image:(NSString *)image selImage:(NSString *)selImage
{
    
    //设置tabbar背景颜色和图片
    UIView *bgView = [[UIView alloc] initWithFrame:self.tabBar.bounds];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.tabBar insertSubview:bgView atIndex:0];
    self.tabBar.opaque = YES;
    
    //添加子控制器
    PGNavigationController *nav = [[PGNavigationController alloc] initWithRootViewController:vc];
    nav.view.backgroundColor = [UIColor whiteColor];
    [self addChildViewController:nav];
    
    //设置基本的属性
    vc.tabBarItem.image = [[UIImage imageNamed:image] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    vc.tabBarItem.selectedImage = [[UIImage imageNamed:selImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

//  vc.tabBarItem.imageInsets = UIEdgeInsetsMake(6,0,-6,0);
    
    self.tabBar.backgroundColor = [UIColor whiteColor];

    self.tabBar.selectedImageTintColor = [UIColor colorWithRed:235/255.0 green:107/255.0 blue:68/255.0 alpha:1.0];
    vc.title = title;
    
}

@end
